package com.cloudkinto.controller.order;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.order.OrderRakutenService;
import com.cloudkinto.service.order.vo.Export2ShipOrderReq;
import com.cloudkinto.service.order.vo.OrderRakutenExportReq;
import com.cloudkinto.service.order.vo.OrderRakutenSysTipsReq;
import com.cloudkinto.service.order.vo.OrderSenderUpdateReq;
import com.cloudkinto.service.order.vo.amazon.OrderBaseInfoUpdateReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-03
 */
@RestController
@Api(tags = "乐天订单模块")
@RequestMapping("/api/admin/rakuten/")
public class OrderRakutenController extends BaseController {

    @Autowired
    private OrderRakutenService service;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit();
    }

    @UserSessionRequired
    @GetMapping("ordersync")
    @ApiOperation(value = "同步订单", notes = "同步订单")
//    @CacheEvict(cacheNames = {"rakutendetail", "rakutenListpage"})
    public SingleResult orderSync(String dateStart, String dateEnd, String dateType, int shopId) {
        int rows = service.orderSync(dateStart, dateEnd, dateType, shopId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("ordersyncInit")
    @ApiOperation(value = "同步订单初始化", notes = "同步订单初始化")
    public SingleResult ordersyncInit() {
        return SingleResult.success(service.ordersyncInit(getCurrentUserId(), getCompanyId()));
    }

    @PostMapping("order/getOrder")
    @ApiOperation(value = "保存日本服务器订单", notes = "保存日本服务器订单")
    public SingleResult getOrderFromJp(@RequestParam("shopId") String shopId, @RequestBody String data) {
        return SingleResult.success(service.getOrderFromJp(false, shopId, data));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
//    @Cacheable(value = "rakutendetail", key = "'rakutendetail'+#id")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

//    @GetMapping("/{orderNumber}")
//    @ApiOperation(value = "根据orderNumber查看详情", notes = "根据orderNumber查看详情")
//    public SingleResult detail(@PathVariable("orderNumber") String orderNumber) {
//        return SingleResult.success("查询成功", service.detail(orderNumber));
//    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    @ApiImplicitParams(@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    /**
     * String dateStart = request.getParameter("dateStart");//订单创建/付款 开始时间
     * String dateEnd = request.getParameter("dateEnd");//订单创建/付款 结束时间
     * String size = request.getParameter("pageSize");
     * String current = request.getParameter("current");
     * String keyword = request.getParameter("keyword");//关键字
     * String shipType = request.getParameter("shipmentType");//发货类型 1 次日达 0 普通
     * String dateType = request.getParameter("dateType"); //订单时间  1创建时间   3付款时间
     * String orderProgress = request.getParameter("orderProgress"); //订单状态
     * String isSend = request.getParameter("isSend");//是否转发货 0 未转 1已转
     * String shopId = request.getParameter("shopId"); //店铺id
     *
     * @return
     */
    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
//    @Cacheable(value = "rakutenListpage",key ="'rakutenListpage'+#dateStart+#dateEnd+#keyword+#shipmentType+#dateType+#orderProgress+#isSend+#shopId+#pageSize+#current" )
    public PageResult listPage(String startDate, String endDate, String keyword, String shipmentType, String dateType,
                               String orderProgress, String isSend, String shopId, Integer pageSize, Integer current) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();

        if (!StringUtils.isEmpty(isSend))
            map.put("isSend", isSend);
        if (!StringUtils.isEmpty(orderProgress))
            map.put("orderProgress", orderProgress);
        if (!StringUtils.isEmpty(shipmentType))
            map.put("shipType", shipmentType);
        if (!StringUtils.isEmpty(keyword))
            map.put("keyword", keyword);
        if (companyId != null)
            map.put("companyId", companyId + "");
        if (!StringUtils.isEmpty(shopId))
            map.put("shopId", shopId);
        map.put("current", current + "");
        map.put("pageSize", pageSize + "");
        map.put("dateStart", startDate);
        map.put("dateEnd", endDate);
        map.put("dateType", endDate);
        return service.getListPage(map);
    }



    /**
     * 把乐天订单组合成发货单
     *
     * @param
     * @return
     */
    @UserSessionRequired
    @PostMapping("export2ShipOrder")
    @ApiOperation(value = "发货", notes = "乐天订单发货")
    public SingleResult export2ShipOrder(@RequestBody Export2ShipOrderReq req) {
        Long companyId = getCompanyId();
        if (req.getIsSolo() == 0) {
            return service.queryOrder2SendOut(req.getOrderids(), getCurrentUserId(), false);
        } else if (req.getOrderids().length > 0) {
            return service.queryOrder2SendOutNoPackage(req.getOrderids()[0], getCurrentUserId(), false, companyId);
        }
        return SingleResult.failure("无数据");
    }

    @UserSessionRequired
    @PostMapping("sendOutMatch")
    @ApiOperation(value = "确定发货", notes = "确定发货")
    public SingleResult sendOutMatch(@RequestBody List<OrderOutputAddReq> orderOutputAddReqList) {
        Long companyId = getCompanyId();
        Long userId = getCurrentUserId();
        return service.sendOutMatch(orderOutputAddReqList, userId, companyId);
    }

    /**
     * 把设置订单已转发货
     *
     * @param orderids
     * @return
     */
    @UserSessionRequired
    @PostMapping("setOrderSend")
    @ApiOperation(value = "标记为发货", notes = "标记为发货")
    public SingleResult setOrderSend(@RequestBody Long[] orderids) {
        Long userId = getCurrentUserId();
        int count = service.setOrderSend(orderids, userId);
        if (count == orderids.length) {
            return SingleResult.success();
        } else {
            return SingleResult.failure(String.format("失败%d条", orderids.length - count));
        }
    }

    /**
     * 编辑系统备注
     *
     * @return
     */
    @UserSessionRequired
    @PostMapping("setOrderSysTips")
    @ApiOperation(value = "编辑系统备注", notes = "编辑系统备注")
    @CacheEvict(value = "rakutendetail", allEntries = true)
    public SingleResult setOrderSysTips(@RequestBody OrderRakutenSysTipsReq req) {
        boolean b = service.setOrderSysTips(req.getId(), req.getDesc(), getCompanyId());
        return SingleResult.success();
    }

    /**
     * 编辑系统备注
     *
     * @return
     */
    @UserSessionRequired
    @PostMapping("updateOrderBaseInfo")
    @ApiOperation(value = "编辑系统基本信息", notes = "编辑系统信息")
    @CacheEvict(value = "rakutendetail", allEntries = true)
    public SingleResult updateOrderBaseInfo(@RequestBody OrderBaseInfoUpdateReq req) {
        return service.updateOrderBaseInfo(req);
    }

    /**
     * 编辑系统备注
     *
     * @return
     */
    @UserSessionRequired
    @PostMapping("updateOrderSender")
    @ApiOperation(value = "编辑系统发货信息", notes = "编辑系统备注")
    @CacheEvict(value = "rakutendetail", allEntries = true)
    public SingleResult updateOrderSender(@RequestBody OrderSenderUpdateReq req) {
        return service.updateOrderSender(req);
    }

    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderRakutenExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.isEmpty(req.isSend))
            map.put("isSend", req.isSend);
        if (!StringUtils.isEmpty(req.orderProgress))
            map.put("orderProgress", req.orderProgress);
        if (!StringUtils.isEmpty(req.shipmentType))
            map.put("shipType", req.shipmentType);
        if (!StringUtils.isEmpty(req.keyword))
            map.put("keyword", req.keyword);
        if (companyId != null)
            map.put("companyId", companyId + "");
        if (!StringUtils.isEmpty(req.shopId))
            map.put("shopId", req.shopId);
        map.put("current", req.current + "");
        map.put("pageSize", req.pageSize + "");

        map.put("dateEnd", req.dateEnd);
        map.put("dateStart", req.dateStart);
        map.put("dateType", req.dateType);
        service.exportExcel(map, req.ids, response);
    }

//    @GetMapping("getShopMsg")
//    @ApiOperation(value = "获取店铺详情", notes = "获取店铺详情")
//    public SingleResult getShopMsg(Long shopId) {
//        service.getShopMsg(shopId);
//        return SingleResult.success();
//    }
}

